import json

from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from .models import Job


def job(request):
    jobs = Job.objects.all()
    return render(request, 'job.html', {'jobs': jobs})


def job_manage(request):
    jobs = Job.objects.all()
    jobs_data = [
        {
            'id': job.id,
            'name': job.name,
            'describe': job.describe,
            'require': job.require,
            'welfare': job.welfare,
            'mode': job.mode
        } for job in jobs
    ]
    return JsonResponse({'jobs': jobs_data})

@require_http_methods(["POST"])
def update_job(request, job_id):
    try:
        data = json.loads(request.body)
        job = Job.objects.get(pk=job_id)
        job.name = data.get('name', job.name)
        job.describe = data.get('describe', job.describe)
        job.require = data.get('require', job.require)
        job.welfare = data.get('welfare', job.welfare)
        job.mode = data.get('mode', job.mode)
        job.save()
        return JsonResponse({'message': 'Job updated successfully'})
    except Job.DoesNotExist:
        return JsonResponse({'error': 'Job not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


@require_http_methods(["DELETE"])
def delete_job(request, job_id):
    try:
        job = Job.objects.get(pk=job_id)
        job.delete()
        return JsonResponse({'message': 'Job deleted successfully'})
    except Job.DoesNotExist:
        return JsonResponse({'error': 'Job not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


@csrf_exempt
def create_job(request):
    if request.method == "POST":
        data = json.loads(request.body)
        job = Job.objects.create(
            name=data['name'],
            describe=data['describe'],
            require=data['require'],
            welfare=data['welfare'],
            mode=data['mode']
        )
        return JsonResponse({'message': 'Job created successfully', 'id': str(job.id)}, status=201)
    else:
        return JsonResponse({'error': 'Invalid HTTP method'}, status=405)
